package com.itheima.web.controller.cargo;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.cargo.*;
import com.itheima.service.cargo.*;
import com.itheima.utils.DownloadUtil;
import com.itheima.web.controller.BaseController;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/cargo/finance")
public class FinanceController extends BaseController {

    @Reference
    private FinanceService financeService;

    @Reference
    private ContractProductService contractProductService;

    @Reference
    private InvoiceService invoiceService;

    @Reference
    private ShippingOrderService shippingOrderService;

    @RequestMapping(value = "/list", name = "财务列表查询")
    public String contractList(@RequestParam(value = "page", defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "10") Integer pageSize) {

        FinanceExample financeExample = new FinanceExample();
        PageInfo pageInfo = financeService.findByPage(pageNum, pageSize, financeExample);

        request.setAttribute("page", pageInfo);

        return "cargo/finance/finance-list";
    }

    @RequestMapping(value = "/toAdd", name = "跳转财务添加页面")
    public String toAdd(String id) {

        request.setAttribute("invoiceId", id);

        return "cargo/finance/finance-add";
    }

    @RequestMapping(value = "/add", name = "财务添加")
    public String add(Finance finance) {

        finance.setFinanceId(UUID.randomUUID().toString());

        finance.setCreateBy(getUser().getUserName());
        finance.setCreateDept(getUser().getDeptId());
        finance.setCreateTime(new Date());

        financeService.save(finance);

        return "redirect:/cargo/finance/list.do";
    }

    @RequestMapping(value = "/toUpdate", name = "跳转财务修改页面")
    public String toUpdate(String id) {

        Finance finance = financeService.findById(id);
        request.setAttribute("finance", finance);

        return "cargo/finance/finance-update";
    }

    @RequestMapping(value = "/edit", name = "财务修改")
    public String edit(Finance finance) {

        finance.setCreateBy(getUser().getUserName());
        finance.setCreateDept(getUser().getDeptId());

        financeService.update(finance);

        return "redirect:/cargo/finance/list.do";
    }

    @RequestMapping(value = "/delete", name = "删除财务")
    public String delete(String id) {
        financeService.delete(id);
        return "redirect:/cargo/finance/list.do";
    }

    @RequestMapping(value = "/exportE", name = "财务校验")
    public String exportE(String id) {

        Finance finance = financeService.findById(id);
        finance.setState(1);
        financeService.update(finance);

        return "redirect:/cargo/finance/list.do";
    }

    @RequestMapping(value = "/printExcelwithTemplate", name = "财务导出--使用模板")
    public void printExcelwithTemplate(String id) throws IOException {

        Finance finance = financeService.findById(id);
        Invoice invoice = invoiceService.findById(finance.getInvoiceId());
        ShippingOrder shippingOrder = shippingOrderService.findById(finance.getInvoiceId());


        //2 封装execl
        //2-1) 读取模板文件---工作簿
        String realPath = session.getServletContext().getRealPath("/make/xlsprint/template03.xlsx");
        Workbook workbook = new XSSFWorkbook(new FileInputStream(new File(realPath)));

        Sheet sheet = workbook.getSheetAt(0);

        Row row3 = sheet.createRow(2);
        row3.createCell(0).setCellValue(finance.getInputDate());
        row3.createCell(1).setCellValue(invoice.getScNo());

        Row row5 = sheet.createRow(4);
        row5.createCell(0).setCellValue(UUID.randomUUID().toString());
        row5.createCell(1).setCellValue(invoice.getScNo());
        row5.createCell(2).setCellValue(shippingOrder.getLcNo());
        row5.createCell(3).setCellValue("无备注");

        Row row7 = sheet.createRow(6);
        row7.createCell(0).setCellValue(shippingOrder.getShipper());
        row7.createCell(1).setCellValue(shippingOrder.getPortOfLoading());
        row7.createCell(2).setCellValue(shippingOrder.getPortOfDischarge());
        row7.createCell(3).setCellValue(invoice.getTradeTerms());

        int ran = new Random().nextInt(10) + 1;

        List<ContractProduct> productList = contractProductService.findAll(new ContractProductExample());
        Collections.shuffle(productList);

        List<ContractProduct> exportProducts = new ArrayList<>();

        for (int i = 0; i < ran; i++) {
            exportProducts.add(productList.get(i));
        }

        for (int i = 1; i < ran; i++) {
            Row rowi = sheet.createRow(7 + i);
            rowi.createCell(0).setCellValue(exportProducts.get(i).getId());
            rowi.createCell(1).setCellValue(exportProducts.get(i).getFactoryName());
            rowi.createCell(2).setCellValue("个");
            rowi.createCell(3).setCellValue(exportProducts.get(i).getCnumber());
            rowi.createCell(4).setCellValue(exportProducts.get(i).getBoxNum());
            rowi.createCell(5).setCellValue(new Random().nextInt(500));
            rowi.createCell(6).setCellValue(new Random().nextInt(300));
            rowi.createCell(7).setCellValue(exportProducts.get(i).getPrice());
            rowi.createCell(8).setCellValue(exportProducts.get(i).getAmount());
            rowi.createCell(9).setCellValue(exportProducts.get(i).getAmount() * 0.17);
        }


        //3 下载
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        DownloadUtil.download(byteArrayOutputStream, response, "财务" + id + ".xlsx");
    }


}
